<?php

/**
 * Class RequestUtil
 */
class RequestUtil
{
    /**
     * @param string $url
     * @param string $method
     * @param string|null $cookie
     * @param array $requestData
     * @param bool|string $storeCookie
     * @param array $header
     * @return string
     */
    public static function request(
        string $url,
        string $method = 'GET',
        string $cookie = null,
        array $requestData = [],
        $storeCookie = false,
        array $header = []): string
    {
        if (!in_array($method, ['GET', 'POST'])) {
            LogUtil::log(1,"Class RequestUtil: 未验证的参数 method " . date("Y/m/d H:i:s"));
            exit("Invalid params method");
        }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $requestData);
        }

        // 携带cookie
        if (!is_null($cookie) && is_file($cookie)) {
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        }

        // 设置请求头
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HEADER, $header);
        } else {
            curl_setopt($ch, CURLOPT_HEADER, 0);
        }

        // 保存COOKIE
        if ($storeCookie) {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $storeCookie);
        }

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }
}